package kangbo.studentmanagementsystem;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class FileIO {
    private static FileWriter fileWriter;//按写入数据
    private static FileReader fileReader;//按字符读取数据
    private static BufferedReader cf;    //从字符输入流读取文本，缓冲字符，以提供字符，数组和行的高效读取。
    private static BufferedWriter cw;    //文本写入字符输出流，缓冲字符，以提供单个字符，数组和字符串的高效写入
    private static File file1 = new File("src/Input.txt");//输入文件
    private static File file2 = new File("src/Output.txt");//输出文件
    public static void fileWrite(String s) {
        try {
            //True表示新写入的内容会追加在旧内容之后
            fileWriter = new FileWriter(file2, true);
            cw = new BufferedWriter(fileWriter);
            cw.write(s);
        }
        catch (IOException e) {
            e.printStackTrace();//将此throwable和其追溯打印到指定的打印流。
        }
        finally {
            try {
                cw.close();
                fileWriter.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static ArrayList<String> fileRead() {
        try {
            fileReader = new FileReader(file1);
            cf = new BufferedReader(fileReader);
            ArrayList<String> ss = new ArrayList<String>();
            String s1 = "";
            while((s1 = cf.readLine()) != null)
                ss.add(s1);
            return ss;
        }
        catch (FileNotFoundException e) {//打开文件失败。
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try{
                cf.close();
                fileReader.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}